import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Scanner;

/**
 * 使用预编译SQL实现网站注册功能
 * 1.定义SQL[占位符?]
 * 2.创建预编译SQL执行对象
 * 3.设置 ? 的值
 * 4.执行SQL语句
 * 5.处理执行结果
 */
public class JDBCReg {
    public static void main(String[] args){
        //1.接收用户输入
        Scanner scanner = new Scanner(System.in);
        System.out.println("请输入用户名:");
        String username = scanner.nextLine();
        System.out.println("请输入密码:");
        String password = scanner.nextLine();
        System.out.println("请输入昵称:");
        String nickname = scanner.nextLine();
        System.out.println("请输入年龄:");
        int age = scanner.nextInt();
        //2.数据库操作
        try (Connection connection = DBUtil.getConnection();){
            //查询语句:用于确认用户名是否被占用
            String sql1 = "SELECT id FROM userinfo WHERE username=?";
            PreparedStatement ps1 = connection.prepareStatement(sql1);
            ps1.setString(1, username);
            ResultSet rs1 = ps1.executeQuery();
            if (rs1.next()){ //被占用
                System.out.println("用户名已被占用");
            }else{//执行注册流程
                String sql2 = "INSERT INTO userinfo(username,password,nickname,age) VALUES(?,?,?,?)";
                PreparedStatement ps2 = connection.prepareStatement(sql2);
                ps2.setString(1, username);
                ps2.setString(2, password);
                ps2.setString(3, nickname);
                ps2.setInt(4, age);
                int i = ps2.executeUpdate();
                System.out.println("注册成功");
            }
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
    }
}
